<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use think\Db;

/**
 * 会员接口
 */
class User extends Api
{
//    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
//    protected $noNeedRight = '*';

    protected $noNeedLogin = [];
    protected $noNeedRight = [];

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }



    /**
     * 我的、会员中心
     */
    public function info()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        // 获取 user 信息
        $user = model('user')->infos($data_array);
        $this->success('查询成功', $user);
    }
    
    
    
    /*用户编辑*/
    public function editUser()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        // 获取 user 信息
        $user = model('user')->editUser($data_array);
        $this->success('查询成功', $user['data']);
    }



    /*
     * 昵称，头像填入
     */
    public function wxFillIn()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json  = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        // 获取 user 信息
        $user = model('user')->wxFillIn($data_array);
        $this->success('查询成功', $user['data']);
    }
    
    /*
     * 爱心值
     * */
    public function pool()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        // 获取 user 信息
        $user = model('user')->pools($data_array);
        $this->success('查询成功', $user);
    }

    /*
     * 优惠券
     * */
    public function coupons()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        // 获取 user 信息
        $user = model('user')->coupons($data_array);
        $this->success('查询成功', $user);
    }

    /*
     * 我的钱包
     * */
    public function wallet()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        // 用户id
        $user = model('user')->wallets($data_array);
        $this->success('查询成功',$user);
    }




    /*
     * 地址列表
     * */
    public function addList()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->addLists($data_array);
        $this->success('查询成功',$res);
    }


    /*
     * 新增地址
     * */
    public function address()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->address($data_array);
        if(empty($res['code'])){
            $this->error($res['msg']);
        }else{
            $this->success($res['msg']);
        }
    }

    /*
     * 地址返参
     * */
    public function addressResult()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->addressResults($data_array);
        $this->success('查询成功', $res);
    }

    /*
     * 地址修改
     * */
    public function editAddress()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->editAddress($data_array);
        if(empty($res['code'])){
            $this->error($res['msg']);
        }else{
            $this->success($res['msg']);
        }
    }

    /*
     * 地址删除
     * */
    public function addressDel()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->addressDels($data_array);
        if(empty($res['code'])){
            $this->error($res['msg']);
        }else{
            $this->success($res['msg']);
        }
    }


    
    /*
     *  捐赠爱心值
     * */
    public function integer()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->integers($data_array);
        if(empty($res['code'])){
            $this->error($res['msg']);
        }else{
            $this->success($res['msg']);
        }
    }


    /*
     * 提现
     * */
    public function withdraw()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->withdraws($data_array);
        if(empty($res['code'])){
            $this->error($res['msg']);
        }else{
            $this->success($res['msg']);
        }

    }
    
    
    /*
     * 提现返参
     * */
    public function withResult()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->withResults($data_array);
        $this->success('查询成功',$res);
    }


    /*
     * 充值
     * */
    public function recharge()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->recharges($data_array);
        if($res['code'])
        {
            $this->success($res['code'],$res['data']);
        }else{
            $this->success($res['msg']);
        }
    }

    /*
     * 开通vip
     * */
    public function open()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->opens($data_array);
        if($res['code'])
        {
            $this->success($res['msg'],$res['data']);
        }else{
            $this->error($res['msg']);
        }
    }



    /*
     * 团长端-团长信息
     * */
    public function team()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->teams($data_array);
        if(empty($res['code'])){
            $this->error($res['msg']);
        }else{
            $this->success($res['msg'],$res['data']);
        }
    }


    /*
     * 团长提现记录
     * */
    public function cashOut()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->cashOuts($data_array);
        $this->success('查询成功',$res);
    }


    /*
     *  团队信息
     * */
    public function group()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->groups($data_array);
        $this->success('查询成功',$res);
    }

    
    /*
     * 团队-我的明细
     * */
    public function my()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->mys($data_array);
        $this->success('查询成功',$res);
    }
    

    /*
     * 团长提现
     * */
    public function teamCashOut()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->teamCashOuts($data_array);
        if($res['code'])
        {
            $this->success($res['msg'],$res['data']);
        }else{
            $this->error($res['msg']);
        }
    }


    /*
     * 团长提现返参
     * */
    public function teamCashOutResult()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->teamCashOutResults($data_array);
        $this->success('查询成功',$res);
    }


    /*
     * 银行卡列表
     * */
    public function bankCard()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->bankCards($data_array);
        $this->success('查询成功',$res);
    }


    /*
     * 添加银行卡
     * */
    public function addBank()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $res  = model('User')->addBanks($data_array);
        if($res['code'])
        {
            $this->success($res['msg']);
        }else{
            $this->error($res['msg']);
        }
    }

    /*
     * 爱心值规则
     * */
    public function rule()
    {
        $res  = model('User')->rules();
        $this->success('查询成功',$res);
    }
    

    /*
     * 生成二维码
     * */
    public function qrCode()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);

        header('content-type:text/html;charset=utf-8');
        $config    = config('mini_program');
        $APPID     = $config['app_id'];
        $APPSECRET = $config['secret'];
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";

        //缓存access_token
        session_start();
        $_SESSION['access_token'] = "";
        $_SESSION['expires_in'] = 0;

        $ACCESS_TOKEN = "";
        if(!isset($_SESSION['access_token']) || (isset($_SESSION['expires_in']) && time() > $_SESSION['expires_in']))
        {

            $json = $this->httpRequest($access_token);

            $json = json_decode($json,true);
            // var_dump($json);
            $_SESSION['access_token'] = $json['access_token'];
            $_SESSION['expires_in'] = time()+7200;
            $ACCESS_TOKEN = $json["access_token"];
        }
        else{
            $ACCESS_TOKEN =  $_SESSION["access_token"];
        }

        $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";
        $param = json_encode(array("path"=>"pages/index/index?pid=".$data_array['user_id'],"width"=> 150));
        $path  = "uploads/" . date('Ymd',time()).'/';
        //POST参数
        $result = $this->httpRequest( $qcode, $param,"POST");
        //生成二维码
        file_put_contents("qrcode.png", $result);
        $base64_image ="data:image/jpeg;base64,".base64_encode( $result );
        $img = $this->base64_image_content($base64_image,$path);
        $url = config('fastadmin.api_url');
//        $qrcode = Db::name('user')->where('id',$data_array['user_id'])->value('qrcode');
        Db::name('user')->where('id',$data_array['user_id'])->update(['qrcode'=>$img]);
        $qrcode = $url.'/'.Db::name('user')->where('id',$data_array['user_id'])->value('qrcode');
        // return $qrcode;
        $this->success('成功',['qrcode'=>$qrcode]);
    }



    function httpRequest($url, $data='', $method='GET'){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if($method=='POST')
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '')
            {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    public function base64_image_content($base64_image_content,$path)
    {
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $new_file = $path;
            if(!file_exists($new_file)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0700);
            }
            //解决base64转码过程中+变成空格的乱码问题
            $new_file = $new_file.time().".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '',str_replace(' ','+',$base64_image_content))))){
                return $new_file;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }


    /*
      * 地址
      * */
    public function addressReturn()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json,true);
        $data = model('User')->addressReturns($data_array);
        $this->success('成功',$data);
    }






    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    
}
